from django.db import models
from django.contrib.auth import get_user_model
from ckeditor.fields import RichTextField
from ckeditor_uploader.fields import RichTextUploadingField
from users.models import Structure
User = get_user_model()


class Category(models.Model):
    """
    通知分类
    """
    name = models.CharField(max_length=128, verbose_name='分类名', blank=False, null=False)
    # alias = models.CharField(max_length=128, verbose_name='别名', db_index=True)
    # date = models.DateTimeField(verbose_name='创建日期', auto_now_add=True)
    # display = models.BooleanField(verbose_name='显示', default=True, db_index=True)
    sort = models.IntegerField(verbose_name='排序', default=0, db_index=True)

    class Meta:
        verbose_name = "通知分类"
        verbose_name_plural = "通知分类"

    def __str__(self):
        return self.name

class News(models.Model):
    """
    通知
    """
    title = models.CharField(max_length=256, verbose_name='标题', blank=False, null=False)
    content = RichTextUploadingField(verbose_name="资料内容")
    category = models.ForeignKey(Category, on_delete=models.SET_NULL, blank=False, null=True, verbose_name='分类',
                                 db_index=True)
    author = models.ForeignKey(User,related_name='news_author',on_delete=models.SET_NULL, verbose_name='发布者', null=True)
    createdate = models.DateTimeField(verbose_name='创建日期', auto_now_add=True)
    pubdate = models.DateTimeField(verbose_name='发布日期', blank=True, null=True)
    updatedate = models.DateTimeField(verbose_name='更新日期', blank=True, null=True)
    # type_choices = ((0, "所有人员"), (1, "指定人员"))
    # type = models.CharField(max_length=20, choices=type_choices, default="0", verbose_name="可见范围")
    status = models.BooleanField(default=True, verbose_name="是否有效")
    is_all = models.BooleanField(default=True, verbose_name="是否所有人可见")


    # togroups =models.ManyToManyField(Structure, verbose_name='接收部门')
    users = models.ManyToManyField(User,through='News2User',verbose_name='接收者')

    class Meta:
        verbose_name = "通知"
        verbose_name_plural = "通知管理"

    def __str__(self):
        return self.title

class News2User(models.Model):
    """
    通知已读
     """
    news = models.ForeignKey(News, on_delete=models.SET_NULL, verbose_name='通知', null=True)
    user = models.ForeignKey(User, on_delete=models.SET_NULL, verbose_name='读者', null=True)
    isreaded = models.BooleanField(default=0, verbose_name="是否已读")
    isdeleted = models.BooleanField(default=0, verbose_name="是否已删")


    class Meta:
        verbose_name = "阅读情况"
        verbose_name_plural = "阅读情况"